// 认证相关路由配置

const Router = require('@koa/router');
const mongoose = require('mongoose');
const config = require('../../project.config');
const jwt = require('jsonwebtoken');
const UserModel = mongoose.model('User');
const InviteCodeModel = mongoose.model('InviteCode');

const router = new Router({
  prefix: '/auth',
});

// 注册接口
router.post('/register', async (ctx) => {
  console.log('--> 调用接口 get /auth/register');
  const { username, password, inviteCode } = ctx.request.body;

  // 字段空值校验
  if (username === '' || password === '' || inviteCode === '') {
    ctx.body = {
      msg: '字段不能为空',
      code: 0,
      data: null,
    };
    return;
  }

  const findCode = await InviteCodeModel.findOne({
    code: inviteCode,
  }).exec();

  if (!findCode || findCode.user !== '') {
    ctx.body = {
      msg: '邀请码无效,或已经被使用',
      code: 0,
      data: null,
    };
    return;
  }

  const findUser = await UserModel.findOne({
    username,
  }).exec();

  if (findUser) {
    ctx.body = {
      msg: '用户已存在',
      code: 0,
      data: null,
    };
    return;
  }

  const user = new UserModel({
    username,
    password,
  });

  const data = await user.save();
  findCode.user = data._id;
  findCode.updatedAt = new Date().getTime();
  findCode.save();

  ctx.body = {
    msg: `注册成功`,
    code: 1,
    data,
  };
});

// 登录接口
router.post('/login', async (ctx) => {
  console.log('--> 调用接口 get /auth/login');
  const { username, password } = ctx.request.body;

  // 字段空值校验
  if (username === '' || password === '') {
    ctx.body = {
      msg: '字段不能为空',
      code: 0,
      data: null,
    };
    return;
  }

  const one = await UserModel.findOne({
    username,
    password,
  }).exec();

  if (!one) {
    ctx.body = {
      msg: '用户名或者密码错误',
      code: 0,
      data: null,
    };
    return;
  }

  const userInfo = {
    username: one.username,
    character: one.character,
    _id: one._id,
  };

  ctx.body = {
    msg: '登录成功',
    code: 1,
    data: {
      user: userInfo,
      token: jwt.sign(userInfo, config.JWT_SECRET),
    },
  };
});

module.exports = router;
